from machine import SPI, I2C, Pin
from drivers import vs1003
from drivers import ssd1306
from drivers.font.symbol import HEART
from utime import sleep, sleep_ms
import test
from config import Config
from server.udp_server import UDPServer
from server.tcp_server import TCPServer
from wifihandler import WifiHandler
import utils
import _thread


def init_player():
	spi = SPI(1)
	spi.init(
		sck=Pin(14),  # in
		mosi=Pin(13),  # in
		miso=Pin(12),  # out
		baudrate=vs1003.BAUDRATE_COMMAND
		# polarity=0,
		# phase=0
	)

	player = vs1003.Player(
		spi,
		xdcs=Pin(26, Pin.OUT, value=1),
		xcs=Pin(25, Pin.OUT, value=1),
		dreq=Pin(33, Pin.IN),
		rst=Pin(32, Pin.OUT, value=1)
	)

	# player.set_volume(0.2)

	return player


player = init_player()
chunks = bytearray()


def start_udp_server(host, port, callback):
	udp_server = UDPServer(host, port, player, callback)

	udp_server.start()


def stop_udp_server():
	try:
		_thread.exit_thread()
	except SystemExit:
		pass


def start_tcp_client(host, port, path, myPlayer, callback):
	tcp_client = TCPServer(host, port, path, myPlayer, callback)

	tcp_client.start()


# enable_play = False
def tcp_callback(data: bytes, index: int):
	global chunks
	# global enable_play

	# if not enable_play:
	# 	if "\r\n\r\n" in data:
	# 		print("index:", index, "data:", data)
	# 		enable_play = True
	# else:
	# print("play")

	# chunks.extend(data)
	print("play chunk", index)
	for i in range(0, round(len(data) / 32)):
		byte = data[i*32:(i+1)*32]
		player.play_chunk(byte)
	print("end of chunk", index)
	# player.play_chunk(data)


def playback_tcp_chunks():
	global chunks

	while True:
		if len(chunks):
			data = chunks[0:32]

			chunks = chunks[32:]

			player.play_chunk(data)


def udp_callback(data: bytes):
	pass
	# player.play_chunk(data[20:])
	# read_data = bytes(32)
	#
	# for count in range(20, len(data), 32):
	# 	# print(data[count:count+32])
	# 	player.play_chunk(data[count:count+32])

		# print(data[count * 32 + 20:len(data) - 20])
		# player.play_chunk(data[count * 32:32])

	# player.play_chunk(data)
	# player.play_test()


radio_stations = [
	["149.255.59.163", 8062, "/1"],
	["192.168.0.157", 80, "/art.mp3"],
	["walkline.wang", 80, "/music.mp3"],
	["50.7.99.155", 7208, "/stream"]
]


def main():
	if Config.SWITCH_MODE == Config.SWITCH_MODE_BROADCASTING:
		result_code = WifiHandler.set_sta_mode(Config.WIFI_STA_SSID, Config.WIFI_STA_PASS)
		WifiHandler.set_ap_status(False)

		# start udp server
		if result_code == WifiHandler.STATION_CONNECTED:
			host = utils.gateway_to_udp_host(WifiHandler.gateway())
			port = Config.UDP_PORT

			_thread.start_new_thread(start_udp_server, (host, port, udp_callback))
			# start_udp_server(host, port, udp_callback)
	elif Config.SWITCH_MODE == Config.SWITCH_MODE_INTERNET_RADIO:
		result_code = WifiHandler.set_sta_mode(Config.WIFI_STA_SSID, Config.WIFI_STA_PASS)
		WifiHandler.set_ap_status(False)

		if result_code == WifiHandler.STATION_CONNECTED:
			# host = "149.255.59.162"
			# port = 8062
			# path = "/1"

			# host = "192.168.0.157"
			# port = 80
			# path = "/art.mp3"

			# host = "walkline.wang"
			# port = 80
			# path = "/music.mp3"

			station = radio_stations[2]
			_thread.start_new_thread(start_tcp_client, (station[0], station[1], station[2], player, tcp_callback))
			# _thread.start_new_thread(playback_tcp_chunks, ())

	# start_tcp_client(host, port, player, tcp_callback)
	else:
		print("Byebye")


def main_midi():
	player.reset()

	with open("moon.mid", mode="rb") as midi:
		player.play_chunk(midi.read(32))


def main_mp3():
	test.run_decoder_mp3_test(player)


def main_wave():
	player.reset()

	with open("media/test.wav", mode="rb") as wav:
		while True:
			data = wav.read(32)

			if not data:
				break

			# print(data, end='')
			player.play_chunk(data)


def main_mp3_2(myPlayer):
	myPlayer.reset()

	print("start play mp3")

	with open("music.mp3", "rb") as mp3:
		while True:
			data = mp3.read(1)

			if not data:
				break

			# for i in data:
			# 	# print(i, end=', ')
			# 	myPlayer.play_chunk(bytes([i]))

			player.play_chunk(data)
			# else:
			# 	break

			# sleep(0.02)

	print("stop play mp3")


def main_sine():
	test.run_decoder_sine_test()


if __name__ == "__main__":
	try:
		# main_wave()
		main()
		# test.run_decoder_test()
		# main_midi()
		# main_mp3()

		# import _thread
		# _thread.start_new_thread(main_mp3_2, ())

		# main_mp3_2(player)

		# test.run_decoder_mp3_test(player)
		# test.run_decoder_sine_test()
		# test.run_oled_test()

	except KeyboardInterrupt:
		print("\nPRESS CTRL+D TO RESET DEVICE")
